#include "scope.h"

Scope::Scope()
{
    Envs.push_back(std::make_shared<Env>());
}

void Scope::EnterScope()
{
    Envs.push_back(std::make_shared<Env>());
}

void Scope::ExitScope()
{
    Envs.pop_back();
}

void Scope::AddVarSymbol(SymbolKind kind, CType *ty, llvm::StringRef name)
{
    auto symbol = std::make_shared<Symbol>(kind, ty, name);
    auto env = std::make_shared<Env>();
    env->VariableSymbolTable.insert({name, symbol});
    Envs.push_back(env);
}

std::shared_ptr<Symbol> Scope::FindVarSymbol(llvm::StringRef name)
{
    for (auto it = Envs.rbegin(); it != Envs.rend(); it++)
    {
        auto &table = (*it)->VariableSymbolTable;
        if (table.count(name) > 0)
        {
            return table[name];
        }
    }
    return nullptr;
}

std::shared_ptr<Symbol> Scope::FindVarSymbolInCurEnv(llvm::StringRef name)
{
    auto &table = Envs.back()->VariableSymbolTable;
    if (table.count(name) > 0)
    {
        return table[name];
    }
    return nullptr;
}